
<template>
    <div class="pres-comp-herb-comp">
        <TitleBox type=2>
            <template #titlecont>
                <span v-lang="{lang: controlSto.language, lgid: -19}">Herb</span>
            </template>
        </TitleBox>
        <!-- TODO 2个echart -->
        <div class="chart-box">
            <div class="chart-img-wrap">
                <uiEchart :config="barOption" id="barChart" style="position: relative;" :vt="dataObj.echartoptVt1" ref="barChart"/>
            </div>

            <div class="chart-img-wrap">
                <uiEchart :config="optionChartPie" id="pieChart" :vt="dataObj.echartoptVt1" ref="pieChart"/>
            </div>
        </div>

        <div class="condition-box">
            <div class="condition-left">
                <SearchDrop class="cond-item">
                    <template #title>
                        <span v-lang="{lang: controlSto.language, lgid: -44}">List sort</span>
                    </template>
                    <template #dropcont>
                        <div class="cond-drop-cont-wrap">
                            <el-radio-group v-model="condObj.sort" @change="toSearch">
                                <div class="cond-radio-wrap">
                                    <el-radio class="cond-radio-item" value="Asc"><span v-lang="{lang: controlSto.language, lgid: -49}"></span></el-radio>
                                    <el-radio class="cond-radio-item" value="Desc"><span v-lang="{lang: controlSto.language, lgid: -50}"></span></el-radio>
                                </div>
                            </el-radio-group>
                        </div>
                    </template>
                </SearchDrop>
                <SearchDrop class="cond-item">
                    <template #title>
                        <span v-lang="{lang: controlSto.language, lgid: -48}">Flavor</span>
                        <!-- <el-popover placement="top-start">
                            <el-checkbox class="all-choose-cls"
                                v-model="condObj.FlavorAll"
                                @change="allChooseFlavor"
                            >
                            <span @click.stop="condObj.FlavorAll = !condObj.FlavorAll" v-lang="{lang: controlSto.language, lgid: -130}">select all</span>
                        </el-checkbox>
                            <template #reference>
                                <span v-lang="{lang: controlSto.language, lgid: -48}">Flavor</span>
                            </template>
                        </el-popover> -->
                    </template>
                    <template #dropcont>
                        <div class="cond-drop-cont-wrap">
                            <el-checkbox class="all-choose-cls"
                                v-model="condObj.FlavorAll"
                                @change="allChooseFlavor"
                            >
                                <span @click.stop="condObj.FlavorAll = !condObj.FlavorAll" v-lang="{lang: controlSto.language, lgid: -130}">select all</span>
                            </el-checkbox>
                            <el-checkbox-group v-model="condObj.flavorList" @change="toSearch">
                                <div class="cond-chbox-wrap">
                                    <el-checkbox class="cond-chbox-item" v-for="item in dataObj.flavorList" :key="'flavor_' + item.id" :value="item.flavorCode" :label="item.flavorName"  />
                                </div>
                            </el-checkbox-group>
                        </div>
                    </template>
                </SearchDrop>

                <SearchDrop class="cond-item">
                    <template #title>
                        <span v-lang="{lang: controlSto.language, lgid: -47}">Property</span>
                        <!-- <el-popover placement="top-start">
                            <el-checkbox class="all-choose-cls"
                                v-model="condObj.PropertyAll"
                                @change="allChooseProperty"
                            >
                            <span @click.stop="condObj.PropertyAll = !condObj.PropertyAll" v-lang="{lang: controlSto.language, lgid: -130}">select all</span>
                        </el-checkbox>
                            <template #reference>
                                <span v-lang="{lang: controlSto.language, lgid: -47}">Property</span>
                            </template>
                        </el-popover> -->
                    </template>
                    <template #dropcont>
                        <div class="cond-drop-cont-wrap">
                            <el-checkbox class="all-choose-cls"
                                v-model="condObj.PropertyAll"
                                @change="allChooseProperty"
                            >
                                <span @click.stop="condObj.PropertyAll = !condObj.PropertyAll" v-lang="{lang: controlSto.language, lgid: -130}">select all</span>
                            </el-checkbox>
                            <el-checkbox-group v-model="condObj.propList" @change="toSearch">
                                <div class="cond-chbox-wrap">
                                    <el-checkbox class="cond-chbox-item" v-for="item in dataObj.proptyList" :key="'prop_' + item.id" :value="item.propertyCode" :label="item.propertyName"  />
                                </div>
                            </el-checkbox-group>
                        </div>
                    </template>
                </SearchDrop>


                <SearchDrop class="cond-item">
                    <template #title>
                        <span v-lang="{lang: controlSto.language, lgid: -85}">Meridians</span>
                        <!-- <el-popover placement="top-start">
                            <el-checkbox class="all-choose-cls"
                                v-model="condObj.MeridiansAll"
                                @change="allChooseMeridians"
                            >
                            <span @click.stop="condObj.MeridiansAll = !condObj.MeridiansAll" v-lang="{lang: controlSto.language, lgid: -130}">select all</span>
                        </el-checkbox>
                            <template #reference>
                                <span v-lang="{lang: controlSto.language, lgid: -85}">Meridians</span>
                            </template>
                        </el-popover> -->
                    </template>
                    <template #dropcont>
                        <div class="cond-drop-cont-wrap">
                            <el-checkbox class="all-choose-cls"
                                v-model="condObj.MeridiansAll"
                                @change="allChooseMeridians"
                            >
                            <span @click.stop="condObj.MeridiansAll = !condObj.MeridiansAll" v-lang="{lang: controlSto.language, lgid: -130}">select all</span>
                            </el-checkbox>
                            <el-checkbox-group v-model="condObj.meridiansList" @change="toSearch">
                                <div class="cond-chbox-wrap">
                                    <el-checkbox class="cond-chbox-item" v-for="item in dataObj.meridiansList" :key="'specy_' + item.id" :value="item.meridiansCode" :label="item.meridiansName"  />
                                </div>
                            </el-checkbox-group>
                        </div>
                    </template>
                </SearchDrop>
            </div>
            <div class="condition-right">
                <div class="ipt-cont">
                    <el-input class="ipt-search" clearable="true" v-model="condObj.searchword" autofocus :placeholder="searchPlace" />
                </div>
                <SearchBtn class="search-item" @click.stop="toSearch"/>

                <TableFilter class="search-item" :column="dataObj.columnList" :filterKey="condObj.filterKey" @onChg="chgTableCol"/>

                <SearchLoad
                    type="prescriptionHerb"
                    :uiCode="condObj.uiCode"
                    :para="{'content': condObj.searchword,'herbFlavor': condObj.flavorList.join(','), 'herbProperty': condObj.propList.join(','), 'langCode': controlSto.language == 1 ? 'ENG' : 'CHN', 'pxId': detailId, 'uiTypeCode': condObj.uiCode, 'herbMeridians': condObj.meridiansList.join(',')}"
                />
            </div>
        </div>

        <div class="cont-box">
            <uiTable
                :config="dataObj.tableConfig"
                :columnConfig="dataObj.columnConfig" 
                :data="dataObj.dataList"
                :loading="isLoading"
                :key="dataObj.searchTablevt">
                <template #[condObj.idField]="{ row }">
                    <div class="jump-box" @click.stop="toClkItem(row)"><span>{{row[condObj.idField]}}</span></div>
                </template>
                <template #[condObj.nameField]="{ row }">
                    <el-tooltip placement="top" :content="row[condObj.nameField]">
                        <div class="jump-box herb-jump-name" @click.stop="toClkItem(row)"><span>{{row[condObj.nameField]}}</span></div>
                    </el-tooltip>
                    <!-- <div class="jump-box" @click.stop="toClkItem(row)"><span>{{row[condObj.nameField]}}</span></div> -->
                </template>
            </uiTable>
            <div class="page-box" v-if="condObj.total > 10">
                <uiPagination
                    :total="condObj.total" :pageSize="condObj.pageSize" :pageIndex="condObj.pageIndex"
                    @onSizeChange="chgSize" @onCurrentChange="chgCurrnt"/>
            </div>
        </div>
    </div>
</template>

<script setup>
    import { ref, reactive, toRefs, computed, onBeforeMount, watch, onMounted } from 'vue'
    import TitleBox from '@/components/TitleBox.vue'
    import SearchBtn from '@/components/SearchBtn.vue'
    import uiEchart from '@/components/ui-echart.vue'
    import TableFilter from '@/components/TableFilter.vue'
    import SearchLoad from '@/components/SearchLoad.vue'
    import uiTable from '@/components/ui-table.vue'
    import uiPagination from '@/components/ui-pagination.vue'
    import SearchDrop from '@/components/SearchDrop.vue'
    import { useRouter } from 'vue-router'

    import { langTxt, getFilterThArr, getFilterLangArr, computedgraphOptions } from '@/utils/util'
    import { getTableThList,
        getPrescriptionCompHerb,
        getHerbFlavorList,
        getHerbPropertyList,
        getHerbmeridiansList,
        getStatisticPrescriptionHerb
    } from '@/service/tcm'

    import { controlStore } from '@/stores/control'
    // import { flavorList, propertyList, merdiansList } from '@/utils/database'
    import { debounce } from 'lodash'

    const emitter = defineEmits(['toCalc']);
    const router = useRouter();
    const props = defineProps({
        detailId: {
            type: [Number, String],
            default: ''
        }
    });
    const { detailId } = toRefs(props);
    const isLoading = ref(true);
    let optionChart = reactive({
        bar: [],
        pie: [],
        barX: []
    })
    const barChart = ref(null);
    const pieChart = ref(null);
    let searchDebounce = null;
    let statisticDebounce = null;

    const controlSto = controlStore();
    const pieTitle = ref(langTxt(controlSto.language, '-102'))
    let optionChartPie = computedgraphOptions(pieTitle.value, '', optionChart.pie, true, 'center')
    const condObj = reactive({
        idField: '100716826576556928',
		nameField: '100716826576556929',
		searchword: '',
		filterKey: 'pres2',
        uiCode: 'prescription_composition_herb',
        word: '',
        sort: 'Asc',
        total: 0,
        pageSize: 10,
        pageIndex: 1,
        flavorList: [],
		propList: [],
		meridiansList: [],
        FlavorAll: true,
		MeridiansAll: true,
		PropertyAll: true
	});

	const dataObj = reactive({
		searchTablevt: 1,
		echartoptVt1: 1,
		columnList: [],
		tableConfig: {
			// size: 'small',
			'tooltip-effect': 'dark',
			'highlight-current-row': true,
			stripe: true,
			'header-cell-style': { background: '#BC9F77', color: '#FFF' },
		},
		columnConfig: [],
		dataList: [],
        flavorList: [],
		proptyList: [],
		meridiansList: [],
	});
    // const flavorListData = reactive([]);
    // const propertyListData = reactive([]);
    // const merdiansListData = reactive([])
    const searchPlace = computed(() => {
		return langTxt(controlSto.language, '-15');
	});
    let barName = ref(langTxt(controlSto.language, '-101'))
    const barOption = {
        title: {
            text: barName.value,
            left: 'center',
            textStyle: {
                fontSize: 14
            }
        },
        toolbox: {
            width: 20,
            itemSize: 20,
            itemGap: 30,
            
            feature: {
                saveAsImage: {
                    title: 'Download',
                    color: '#333333',
                    iconSize: 20,
                    pixelRatio: 2,
                    icon: 'image://',
                    emphasis: {
                        iconStyle: {
                            color: '#ffffff',
                            textBackgroundColor: 'rgba(0, 0, 0, 0.8)',
                            textBorderRadius: 2,
                            textPadding: 5
                        }
                    },
                    iconStyle: {

                    }
                }
            }
        },
        xAxis: {
            type: 'category',
            triggerEvent: true,
            data: optionChart.barX,
            axisLabel: {
                interval:0,
                show: true,
                // rotate:-90,
                formatter: function(value) {
                    // 如果标签长度超过15，将剩余的文字替换为省略号
                    if (value.length > 10) {
                        return value.slice(0, 5) + '...';
                    } else {
                        return value;
                    }
                },
                tooltip: {
                    show: true
                }
            }
            
            // name: 'Names of Chinese Herbal Medicine'
        },
        yAxis: {
            type: 'value',
            show: true,
            nameLocation :'center',
            nameRotate:0,
            axisLine: {
                show: true // 显示Y轴线
            },
            axisLabel: {
                interval: 'auto',
                formatter: function(value) {
                    // 如果数值大于1000，以K作为单位显示
                    if (value >= 10000) {
                        return (value / 1000) + 'w';
                    } else {
                        return value;
                    }
                }
            }
            // name: 'Number of ingredients (pieces)',
        },
        // tooltip: {
        //   trigger: 'axis',
        //   axisPointer: {
        //     // 坐标轴指示器，坐标轴触发有效
        //     type: 'shadow', // 默认为直线，可选为：'line' | 'shadow'
        //   },
        // },
        tooltip: {
            axisPointer: {
                type: 'shadow',
                label: {
                    width: 150
                }
            },
            formatter: (param) => {
                return  `<div style="max-width: 300px;white-space: pre-wrap">${param.data.name} : ${param.data.value}</div>`
            },
        },
        series: [
            {
                data: optionChart.bar,
                barCategoryGap: '5px',
                barMaxWidth: '40px',
                itemStyle: {
                    normal: {
                        color: function(params) {
                            let colorList = ['#5AD8A6', '#5B8FF9', '#F6BD16', '#E8684A', '#9270CA', '#6DC8EC'];
                            let colorItem = colorList[params.dataIndex];
                            return colorItem;
                        }
                    }
                },
                // color: ['#5AD8A6', '#5B8FF9', '#F6BD16', '#E8684A', '#9270CA', '#6DC8EC'],
                type: 'bar',
                // barWidth: '40px'
            }
        ]
    }

    onBeforeMount(()=> {
        // toGetHerbFlavorList();
		// toGetHerbPropertyList();
		// toGetHerbMeridiansList();
        initDebounce();
        // statisticDebounce && statisticDebounce();
		getTableTh();
        getAllData();
        // toGetData();
    });

    const initDebounce = () => {
        statisticDebounce = debounce(e => {
            toGetStatisticPrescriptionHerb()
        }, 400)
        searchDebounce = debounce((e) => {
           getDataList();
        }, 400);
    };
    onMounted(() => {
        
    })
    const toClkItem = (row) => {
        router.push({ name: 'herbdetail' , query: {id: row[condObj.idField]} });
    }
    const toGetStatisticPrescriptionHerb = () => {
        const param = {
            langCode: controlSto.language == 1 ? 'ENG' : 'CHN',
            prescriptionId: detailId.value,
            uiTypeCode: condObj.uiCode,
            herbFlavor: condObj.flavorList.join(','),
            herbProperty: condObj.propList.join(','),
            herbMeridians: condObj.meridiansList.join(','),
            content: condObj.searchword
        }
        getStatisticPrescriptionHerb(param).then(res => {
            // console.log(res)
            if(res.success) {
                let arrBar = [];
                let arrPie = [];
                let arrBarX = [];
                for (let k in res.data.histogramStatistics) {
                    arrBar.push({value: res.data.histogramStatistics[k], name:k});
                    arrBarX.push(k);
                }
                barOption.series[0].data = arrBar;
                barOption.xAxis.data = arrBarX;
                barOption.title.text = langTxt(controlSto.language, '-101');
                barOption.toolbox.feature.saveAsImage.title = controlSto.language == 1 ? 'Download' : '下载';
                barChart.value.initEchart()
                for (let key in res.data.pieStatistics) {
                    arrPie.push({value: res.data.pieStatistics[key], name: key});
                }
                optionChartPie.title.text = langTxt(controlSto.language, '-102');
                optionChartPie.toolbox.feature.saveAsImage.title = controlSto.language == 1 ? 'Download' : '下载';
                optionChartPie.series[0].data = arrPie;
                arrPie.length < 5 ? optionChartPie.legend.top = 'center' : ''
                pieChart.value.initEchart()
            }

        })
    }

    const toGetHerbFlavorList = () => {
        let params = {
            langCode: controlSto.language == 1 ? 'ENG' : 'CHN',
        };
		getHerbFlavorList(params).then((res) => {
            if (res.success && res.data) {
                condObj.flavorList = [];
                dataObj.flavorList = res.data || [];
                dataObj.flavorList.forEach(e => {
                    condObj.flavorList.push(e.flavorCode)
                })
            }
        }).catch(() => {});
    };
	const toGetHerbPropertyList = () => {
        let params = {
            langCode: controlSto.language == 1 ? 'ENG' : 'CHN',
        };
		getHerbPropertyList(params).then((res) => {
            if (res.success && res.data) {
                condObj.propList = [];
                dataObj.proptyList = res.data || [];
                res.data.forEach(e => {
                    condObj.propList.push(e.propertyCode)
                });
            }
        }).catch(() => {});
    };
	const toGetHerbMeridiansList = () => {
        let params = {
            langCode: controlSto.language == 1 ? 'ENG' : 'CHN',
        };
		getHerbmeridiansList(params).then((res) => {
            if (res.success && res.data) {
                condObj.meridiansList = [];
                dataObj.meridiansList = res.data || [];
                dataObj.meridiansList.forEach(e => {
                    condObj.meridiansList.push(e.meridiansCode)
                })
            }
        }).catch(() => {});
    };
    const getTableTh = () => {
        let params = {
            uiCode: condObj.uiCode,
            langCode: 'ENG,CHN'
        };
        getTableThList(params).then((res) => {
            if (res.success) {
                let arr = res.data || [];
                let thArr = getFilterThArr(arr, dataObj.filterKey);
        		let langArr = getFilterLangArr(thArr);
        		controlSto.setLangList(langArr);
        		dataObj.columnList = thArr;
            }
        }).catch(() => {});
    };

    const chgTableCol = (e) => {
		dataObj.columnConfig = e || [];
		dataObj.searchTablevt = new Date().valueOf();
        emitter('toCalc');
    };
    const getAllData = () => {
        let params = {
            langCode: controlSto.language == 1 ? 'ENG' : 'CHN',
        };
        Promise.all([getHerbFlavorList(params), getHerbPropertyList(params), getHerbmeridiansList(params)]).then(res => {
            if (res[0].success && res[0].data) {
                condObj.flavorList = [];
                dataObj.flavorList = res[0].data || [];
                dataObj.flavorList.forEach(e => {
                    condObj.flavorList.push(e.flavorCode)
                })
            }
            if (res[1].success && res[1].data) {
                condObj.propList = [];
                dataObj.proptyList = res[1].data || [];
                res[1].data.forEach(e => {
                    condObj.propList.push(e.propertyCode)
                });
            }
            if (res[2].success && res[2].data) {
                condObj.meridiansList = [];
                dataObj.meridiansList = res[2].data || [];
                dataObj.meridiansList.forEach(e => {
                    condObj.meridiansList.push(e.meridiansCode)
                })
            }
            getDataList();
            toGetStatisticPrescriptionHerb();
        })
    }
    
    const toGetData = () => {
        searchDebounce && searchDebounce();
    };

    const getDataList = () => { // getPrescriptionCompHerb
        let params = {
            langCode: controlSto.language == 1 ? 'ENG' : 'CHN',
            prescriptionId: detailId.value,
            content: condObj.searchword,
            uiTypeCode: condObj.uiCode,
            herbFlavor: condObj.flavorList.join(','),
            herbProperty: condObj.propList.join(','),
            herbMeridians: condObj.meridiansList.join(','),
            sortType: condObj.sort,
			pageNo: condObj.pageIndex || 10,
			pageSize: condObj.pageSize || 1
        };
        isLoading.value = true;
        getPrescriptionCompHerb(params).then((res) => {
            isLoading.value = false;
            if (res.success && res.data && res.data.records) {
                dataObj.dataList = res.data.records || [];
                condObj.total = res.data.totalCount || 0;
            }
        }).catch(() => {
            isLoading.value = false;
        });
        emitter('toCalc');
    };


        
    const chgSize = (e) => {
        condObj.pageSize = e || 10;
        toGetData();
    };
    const chgCurrnt = (e) => {
        condObj.pageIndex = e || 1;
        toGetData();
    };
    const toSearch = () => {
        condObj.word = condObj.searchword;
        condObj.pageIndex = 1;
        toGetData();
    };

    const allChooseMeridians = () => {
		if(condObj.meridiansList.length == dataObj.meridiansList.length) {
			condObj.meridiansList = []
		} else {
			condObj.meridiansList = [];
			dataObj.meridiansList.forEach(e => {
				condObj.meridiansList.push(e.meridiansCode)
			})
		}
	}
	const allChooseProperty = () => {
		if(condObj.propList.length == dataObj.proptyList.length) {
			condObj.propList = []
		} else {
			condObj.propList = [];
			dataObj.proptyList.forEach(e => {
				condObj.propList.push(e.propertyCode)
			})
		}
	}
	const allChooseFlavor = () => {
		if(condObj.flavorList.length == dataObj.flavorList.length) {
			condObj.flavorList = [];
		} else {
			condObj.flavorList = [];
			dataObj.flavorList.forEach(e => {
				condObj.flavorList.push(e.flavorCode)
			})
		}
	}

    watch(() => controlSto.language, (nv, ov) => {
		if(nv != ov && ov) {
			dataObj.echartoptVt1 = new Date().valueOf();
            getAllData();
            // toGetHerbFlavorList();
            // toGetHerbPropertyList();
            // toGetHerbMeridiansList();
            // toGetData();
            // statisticDebounce && statisticDebounce();
		}
	}, { immediate: true });
    watch(() => [condObj.flavorList, condObj.propList, condObj.meridiansList], (n, v) => {
		if(n != v) toSearch()
		if(n[0].length == dataObj.flavorList.length) condObj.FlavorAll = true;
		else condObj.FlavorAll = false;

		if(n[1].length == dataObj.proptyList.length) condObj.PropertyAll = true;
		else condObj.PropertyAll = false;

		if(n[2].length == dataObj.meridiansList.length) condObj.MeridiansAll = true;
		else condObj.MeridiansAll = false;
	}, { immediate: true })

</script>


<style lang="scss" scoped>
    .pres-comp-herb-comp {
        padding-bottom: 24px;
        .chart-box {
            padding: 24px 0 0;
            display: flex;
            justify-content: space-around;
            .chart-img-wrap {
                height: 240px;
                width: 50%;
                max-width: 500px;
                padding: 8px 12px 0;
                &:last-child{
                    margin: 0 0 0 24px;
                }
                // background: #FFFFFF;
                &:hover{
                    background: #FFFFFF;
                    box-shadow: 0px 3px 16px 0px rgba(0,0,0,0.1);
                }
            }
            
        }
        .condition-box {
            display: flex;
            padding: 24px 0;
            justify-content: space-between;
            .condition-left {
                display: flex;
                min-width: 600px;
                .cond-item {
                    margin-right: 16px;
                    width: 20%;
                }
            }
            .condition-right {
                .ipt-cont {
                    display: inline-block;
                    padding-right: 16px;
                    // width: 35%;
                    .ipt-search {
                        // width: 300px;
                    }
                }
                .search-item {
                    margin-right: 16px;
                }
            }
        }
        .cont-box {
            .herb-jump-name {
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }
        }

    //    .chart-box {
    //         height: 400px;
    //         border: 1px solid red;
    //    }
    }
</style>
